#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import threading
from os import path

class dispatcher(object):

    def __init__(self, dispatcher, hosts, 
                 socket=socket, threading=threading):

        conn = {}
        sck = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
        sck.bind(dispatcher)
        sck.listen(10)
        for i in hosts:
            conn[i] = sck.accept()[0]
        th_msg = []
        for i in hosts:
            conn[i].send("OK")
            th_msg.append(threading.Thread(target=self.msg_channel, 
                                           args=[conn[i]]))
            th_msg[-1].start()
        for th in th_msg:
            th.join()

    def msg_channel(self, *args):
        try:
            conn = args[0]
            data = conn.recv(1024)
            while (data):
                print data
                data = conn.recv(1024)
        finally:
            conn.close()

if __name__ == "__main__":
    local_dict = {'HOSTS': {},
                  'DISPATCHER': None,
                  'FS': None,
                  'PROTOCOL': None,
                  'LAMBDA_ARGS': None}
    execfile(path.expanduser('~/.cheops.py'), {}, local_dict)
    globals().update(local_dict)
    print local_dict
    x = dispatcher(DISPATCHER, HOSTS)
    
